package logic

import (
	"context"
	"errors"
	"videos/model/cache"
	"videos/model/mysql"
	"videos/pkg"

	"videos/videorpc/internal/svc"
	"videos/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *videorpc.UpdatePasswordRequest) (*videorpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}

	if user.ID == 0 {
		return nil, errors.New("该用户不存在")
	}

	result, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误")
	}

	if pkg.Md5(in.Password) == pkg.Md5(in.NewPassword) {
		return nil, errors.New("旧密码与新密码一致,不允许修改")
	}

	if pkg.Md5(in.NewPassword) != pkg.Md5(in.SkcNewPassword) {
		return nil, errors.New("两次密码输入不一致,请重新输入")
	}

	user.Password = in.NewPassword

	err = user.UpdatePassword(mysql.DB)
	if err != nil {
		return nil, err
	}

	return &videorpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
